# @Author: Eric Ito
# @Date: 1/26/2009
# @Name: Project Euler Problem 14

"""
The following iterative sequence is defined for the set of positive integers:

n  n/2 (n is even)
n  3n + 1 (n is odd)

Using the rule above and starting with 13, we generate the following sequence:
13  40  20  10  5  16  8  4  2  1
It can be seen that this sequence (starting at 13 and finishing at 1)
 contains 10 terms. Although it has not been proved yet (Collatz Problem),
 it is thought that all starting numbers finish at 1.

Which starting number, under one million, produces the longest chain?
"""

def getChainLength(num):
    counter = 0
    while not num == 1:
        if num % 2 == 0:
            num = num/2
        else:
            num = 3*num + 1
        counter += 1
    return counter

def main():
    i = 999999
    max = 0
    maxStart = 0
    while i > 0:
        tmpMax = getChainLength(i)
        print tmpMax
        if tmpMax > max:
            max = tmpMax
            maxStart = i
        i -= 1
    print tmpMax,maxStart

def main2():
    # we should work backwards and start at 1
    i = 16
    QUEUE = []
    SEQUENCE = []
    SEQUENCE.append(1)
    SEQUENCE.append(2)
    SEQUENCE.append(4)
    SEQUENCE.append(8)
    SEQUENCE.append(16)
    for k in range(1,1000000):
        QUEUE.append(k)
    counter = 1
    while len(QUEUE) > 0:
        if not i % 2 == 0:
            i = i*2
        else:
            i -= 1
            i = i/3
        counter += 1
        try:
            QUEUE.remove(i)
        except:
            pass
        SEQUENCE.append(i)
        print SEQUENCE
    print SEQUENCE

if __name__ == "__main__":
    main()